﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Portal.Nhibernate.Repository;

namespace Portal.Web.Areas.Admin.Controllers
{

    public class CategoryController : BaseAdminController
    {

        private readonly ICategoryRepository<ICategory> _categoryRepository;
        private readonly IList<ICategory> _categoryList = CategoryCache.GetList();
        public CategoryController(ICategoryRepository<ICategory> categoryRepository)
        {
            _categoryRepository = categoryRepository;
        }
        public CategoryController()
        {
            _categoryRepository = new CategoryRepository();
        }
        public ActionResult SearchControl()
        {
            return View();
        }
        public ActionResult SearchProductCategoryControl()
        {
            return View();
        }
        /// <summary>
        /// 分类管理页面
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult GetListJson(QueryModel queryModel, string sort = "Sort", string order = "DESC", int page = 1, int rows = 10)
        {
            var list = _categoryList.AsQueryable().SearchWhere(queryModel).Sorting(sort, order).JqEasyuiDataGrid(page, rows);
            return Json(list);
        }
        public ActionResult GetProductCategoryListJson(string sort = "Sort", string order = "DESC", int page = 1, int rows = 10)
        {
            var list = _categoryList.AsQueryable().Sorting(sort, order).Where(o => o.Type == (int)CategoryTypeEnum.Product).JqEasyuiDataGrid(page, rows);
            return Json(list);
        }

        public ActionResult GetProductTreeJson(string sort = "Sort", string order = "DESC")
        {
            var list = _categoryList;
            return Json(list.Where(o => o.Type == (int)CategoryTypeEnum.Product).Select(o => new JqEasyuiTree { id = o.Id, text = o.Name }));
        }
        public ActionResult GetProductComboBoxJson(string value, string sort = "Sort", string order = "DESC")
        {
            var list = _categoryList.Where(o => o.Type == (int)CategoryTypeEnum.Product).JqEasyuiComboBox(o => new JqEasyuiComboBox { id = o.Id, text = o.Name });
            var selected = list.FirstOrDefault(o => o.id == value);
            if (selected != null) selected.selected = true;
            return Json(list);

        }



        /// <summary>
        /// 创建分类页面
        /// </summary>
        /// <returns></returns>
        public ActionResult Create()
        {
            var model = _categoryRepository.CreateEntity();
            var lastModel = _categoryList.OrderByDescending(o => o.Sort).FirstOrDefault() ?? _categoryRepository.CreateEntity();
            model.Founder = CurrentUserName;
            model.Sort = lastModel.Sort + 1;
            if (Request.IsAjaxRequest())
                return View("CreateControl", model);
            return View(model);
        }
        /// <summary>
        /// 创建分类页面（部分视图 用于AJAX）
        /// </summary>
        /// <returns></returns>
        public ActionResult CreateControl()
        {
            var model = _categoryRepository.CreateEntity();
            var lastModel = _categoryList.OrderByDescending(o => o.Sort).FirstOrDefault() ?? _categoryRepository.CreateEntity();
            model.Founder = CurrentUserName;
            model.Sort = lastModel.Sort + 1;
            return View(model);
        }

        public ActionResult CreateProductCategoryControl()
        {
            var model = _categoryRepository.CreateEntity();
            var lastModel = _categoryList.OrderByDescending(o => o.Sort).FirstOrDefault() ?? _categoryRepository.CreateEntity();
            model.Founder = CurrentUserName;
            model.Sort = lastModel.Sort + 1;
            model.Type = (int)CategoryTypeEnum.Product;
            return View(model);
        }
        public ActionResult EditProductCategoryControl(string id)
        {
            var model = _categoryRepository.Get().SingleOrDefault(o => o.Id == id);
            return View(model);
        }
        /// <summary>
        /// 获取分类所属（大类）
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public ActionResult GetCategoryType(string value = "")
        {
            return Json(EnumDescription.ToList<CategoryTypeEnum>().JqEasyuiComboBox(
                o => new JqEasyuiComboBox { id = ((int)o.Value).ToString(CultureInfo.InvariantCulture), text = o.Key, selected = value == ((int)o.Value).ToString(CultureInfo.InvariantCulture) }));
        }

        /// <summary>
        /// 创建分类页面
        /// </summary>
        /// <param name="collection"></param>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [CacheResetFilterAttribute(CacheKey.CategoryList)]
        public ActionResult Create(FormCollection collection, Category entity)
        {
            var model = _categoryRepository.CreateEntity();
            model.Name = entity.Name;
            model.NameEn = entity.NameEn;

            model.Type = entity.Type;
            model.Sort = entity.Sort;
            _categoryRepository.Add(model);
            _categoryRepository.Save();
            return Json(new AjaxResult { state = true, message = "添加成功" });
        }
        [HttpPost]
        [CacheResetFilterAttribute(CacheKey.CategoryList)]
        public ActionResult CreateJqEsayui()
        {
            var model = _categoryRepository.CreateEntity();
            var lastModel = _categoryList.OrderByDescending(o => o.Sort).FirstOrDefault() ?? _categoryRepository.CreateEntity();
            model.Founder = CurrentUserName;
            model.Sort = lastModel.Sort + 1;
            return Json(model);

        }

        /// <summary>
        /// 编辑分类页面
        /// </summary>
        /// <param name="id">编辑分类ID</param>
        /// <returns></returns>
        public ActionResult Edit(string id)
        {
            var model = _categoryRepository.Get().SingleOrDefault(o => o.Id == id);
            if (Request.IsAjaxRequest())
                return View("EditControl", model);
            return View(model);
        }
        /// <summary>
        /// 编辑分类页面（部分视图 用于AJAX）
        /// </summary>
        /// <param name="id">编辑分类ID</param>
        /// <returns></returns>
        public ActionResult EditControl(string id)
        {
            var model = _categoryRepository.Get().SingleOrDefault(o => o.Id == id);
            return View(model);
        }
        /// <summary>
        /// 编辑保存分类
        /// </summary>
        /// <param name="collection"></param>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [CacheResetFilterAttribute(CacheKey.CategoryList)]
        public ActionResult Edit(FormCollection collection, Category entity)
        {
            var model = _categoryRepository.Get().SingleOrDefault(o => o.Id == entity.Id);
            if (model != null)
            {
                model.Name = entity.Name;
                model.NameEn = entity.NameEn;
                model.Type = entity.Type;

                model.Sort = entity.Sort;
                _categoryRepository.Add(model);
                _categoryRepository.Save();
            }
            return Json(new AjaxResult { state = true, message = "修改成功" });
        }
        /// <summary>
        /// 删除分类
        /// </summary>
        /// <param name="id"></param>
        /// <param name="collection"></param>
        /// <returns></returns>
        [HttpPost]
        [CacheResetFilterAttribute(CacheKey.CategoryList)]
        public ActionResult Delete(IList<string> id, FormCollection collection)
        {

            var list = _categoryList.Where(o => id.Contains(o.Id));
            list.ForEach(o => _categoryRepository.Delete(o));
            _categoryRepository.Save();
            return Json(new AjaxResult { state = true, message = "删除成功" });

        }
    }
}
